﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace PSE.Deployment.Util
{
    public static class Serializer
    {
        public static void Serialize<T>(T config, string filePath)
        {
            Serialize(typeof(T), config, filePath);
        }

        public static string Serialize<T>(T config)
        {
            return Serialize(typeof(T), config);
        }

        public static void Serialize(Type type, object config, string filePath)
        {
            string directory = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            XmlSerializer ser = new XmlSerializer(type);

            using (StreamWriter sw = new StreamWriter(filePath, false))
            {
                ser.Serialize(sw, config);
            }
        }

        public static string Serialize(Type type, object config)
        {
            StringBuilder xml = new StringBuilder();

            XmlSerializer ser = new XmlSerializer(type);

            using (StringWriter sw = new StringWriter(xml))
            {
                ser.Serialize(sw, config);
            }

            return xml.ToString();
        }

        public static T Deserialize<T>(string filePath)
        {
            return (T)Deserialize(typeof(T), filePath);
        }

        public static object Deserialize(Type type, string filePath)
        {
            if (!System.IO.File.Exists(filePath))
                throw new FileNotFoundException(filePath);

            object configDeserialized;

            try
            {
                XmlSerializer serializer = new XmlSerializer(type);

                using (StreamReader sr = new StreamReader(filePath))
                {
                    configDeserialized = serializer.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Não foi possível ler o arquivo '{0}'", filePath), ex);
            }

            return configDeserialized;
        }
    }
}
